// web/src/data/tokens.ts
import {v4 as uuidV4} from 'uuid'
import {getVerificationTokenByEmail} from "@/data/verification-token";
import {db} from "@/lib/db";
import {getPasswordResetTokenByEmail, getPasswordResetTokenByToken} from "@/data/password-reset-token";
import crypto from 'crypto'
import {getTwoFactorTokenByEmail} from './two-factor-token';

export const generateTwoFactorToken = async (email: string) => {
    // 6位随机数
    const token = crypto.randomInt(100_000, 1_000_000).toString()
    // 5min过期
    const expires = new Date(new Date().getTime() + 5 * 60 * 1000)

    const existingToken = await getTwoFactorTokenByEmail(email)
    if (existingToken) {
        await db.twoFactorToken.delete({where: {id: existingToken.id}})
    }

    const twoFactorToken = await db.twoFactorToken.create({
        data: {
            email, token, expires
        }
    })

    return twoFactorToken
}

export const generateVerificationToken = async (email: string) => {
    const token = uuidV4()
    // 一个小时过期
    const expires = new Date(new Date().getTime() + 3600 * 1000)

    const existingToken = await getVerificationTokenByEmail(email)
    if (existingToken) {
        await db.verificationToken.delete({
            where: {id: existingToken.id}
        })
    }

    const verificationToken = await db.verificationToken.create({
        data: {
            email, token, expires
        }
    })
    return verificationToken
}

export const generateResetToken = async (email: string) => {
    const token = uuidV4()
    // 一个小时过期
    const expires = new Date(new Date().getTime() + 3600 * 1000)

    const existingToken = await getPasswordResetTokenByEmail(email)
    if (existingToken) {
        await db.passwordResetToken.delete({
            where: {id: existingToken.id}
        })
    }

    const passwordResetToken = await db.passwordResetToken.create({
        data: {
            email, token, expires
        }
    })
    return passwordResetToken
}

